package com.lhz.project.wage.common;

import com.lhz.common.utils.file.FileUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by LiGezZ on 2019/3/8 22:35
 *
 * @author lihuazhi
 */
@Slf4j
public class ExcelUtil {

    public static void main(String[] args) {
        String name = FileUtil.class.getName();
        System.out.printf(name);
    }

    public static Row setColumnWidth(Sheet sheet, int size, Map<String, Object> colMap) {
        Row row = sheet.createRow(0);
        row.setHeight((short) (300 * 2));
        String[] specials = (String[]) colMap.get("special");
        int def = Integer.parseInt(colMap.get("def").toString());

        //设置默认宽度
        for (int i = 0; i < size; i++) {
            sheet.setColumnWidth(i, def * 256);
        }
        //设置特殊宽度
        for (String special : specials) {
            String[] split = special.split(":");//col:num
            String cols = split[0];
            if (cols.contains("-")) {//特殊单元格为区间值
                String[] split1 = cols.split("-");
                for (String s : split1) {
                    sheet.setColumnWidth(Integer.parseInt(s), Integer.parseInt(split[1]) * 256);
                }
            } else {
                sheet.setColumnWidth(Integer.parseInt(cols), Integer.parseInt(split[1]) * 256);
            }
        }
        return row;
    }

    public static void setHeader(Row row, String header, Sheet sheet, CellStyle headStyle, int size) {
        Cell cellHeader;
        for (int i = 0; i < size; i++) {
            cellHeader = row.createCell(i);
            cellHeader.setCellValue(header);
            cellHeader.setCellStyle(headStyle);
        }
        //合并单元格
        CellRangeAddress region = new CellRangeAddress(0, 0, 0, size - 1);
        sheet.addMergedRegion(region);
    }


    //一级标题
    public static void setTitleOneLevel(Sheet sheet, CellStyle titleStyle, String[] title) {
        //设置单元格名称
        Row row = sheet.createRow(1);
        Cell cell;
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(titleStyle);
        }
    }

    //存在二级标题
    public static void setTitleTwoLevel(int size, Sheet sheet, CellStyle titleStyle, String[] oneTitle, String[] twoTitle) {
        //设置单元格名称
        Row row = sheet.createRow(1);
        Row row2 = sheet.createRow(2);
        row.setHeight((short) (200 * 2));
        row2.setHeight((short) (200 * 2));

        //先将第一行和第二行都设置为二级标题
        Cell cell;
        Cell cell2;
        for (int i = 0; i < twoTitle.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(twoTitle[i]);
            cell.setCellStyle(titleStyle);

            cell2 = row2.createCell(i);
            cell2.setCellValue(twoTitle[i]);
            cell2.setCellStyle(titleStyle);
        }
        //单独为第一级标题设置值 规则(name:colNum:colspan)
        for (String title : oneTitle) {
            String[] split = title.split(":");
            cell = row.createCell(Integer.parseInt(split[1]));
            cell.setCellValue(split[0]);
            cell.setCellStyle(titleStyle);
        }

        //获取需要跨列的单元格集合及跨列数量
        List<Integer> cols = new ArrayList<>();
        List<Integer> colspan = new ArrayList<>();
        for (String title : oneTitle) {
            String[] split = title.split(":");
            cols.add(Integer.valueOf(split[1]));
            colspan.add(Integer.valueOf(split[2]));
        }

        //合并单元格处理
        for (int i = 0; i < size; i++) {
            CellRangeAddress region;
            //一级标题 跨列
            if (cols.contains(i)) {
                //存在跨列单元格
                //取出第一个列号及合并数量
                Integer colNum = cols.get(0);
                Integer spanNum = colspan.get(0);
                //重构i的值为合并的最后一个单元格列号
                i = colNum + spanNum - 1;
                region = new CellRangeAddress(1, 1, colNum, i);
                cols.remove(0);
                colspan.remove(0);
            } else {
                //其他二级标题跨两行处理
                region = new CellRangeAddress(1, 2, i, i);
            }
            sheet.addMergedRegion(region);
        }
    }

    public static List<Row> setRowValue(List<List<Object>> list, int rowNum, Sheet sheet, CellStyle style) {
        List<Row> rowList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            //行数据
            List<Object> objs = list.get(i);
            //遍历数据行，获取列数据
            Row row = sheet.createRow(rowNum + i);
            for (int a = 0; a < objs.size(); a++) {
                //类型转换
                Object obj = objs.get(a);
                Cell cell = row.createCell(a);
                //类型转换
                if (obj instanceof Double) {
                    cell.setCellValue((Double) obj);
                } else if (obj instanceof Date) {
                    cell.setCellValue((Date) obj);
                } else {
                    cell.setCellValue(obj.toString());
                }
                cell.setCellStyle(style);
            }
            rowList.add(row);
        }
        return rowList;
    }

    public static CellStyle setDataAllStyle(Workbook workbook, String type) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("等线");//默认等线字体
        if ("head".equals(type)) {
            font.setFontHeightInPoints(Short.parseShort("16"));
            font.setBold(true);//加粗
        } else if ("title".equals(type)) {
            font.setBold(true);//加粗
            font.setFontHeightInPoints(Short.parseShort("12"));
        } else if ("num".equals(type)) {
            font.setFontHeightInPoints(Short.parseShort("12"));
            style.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));//保留2位小数点
        } else if ("sum".equals(type)) {
            font.setFontHeightInPoints(Short.parseShort("10"));
            style.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));//保留2位小数点
            style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());//设置背景色
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        } else {
            font.setFontHeightInPoints(Short.parseShort("12"));
        }
        style.setWrapText(true);
        style.setFont(font);
        //设置边框
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        //设置居中
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }


    public static void outExcel(Workbook workbook, String fileName, HttpServletResponse response) {
        try {

            //fileName = new String(fileName.getBytes(), "UTF-8");//有没有这句话
            response.reset();
            response.setHeader("Content-Type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            //将excel写入到输出流中
            workbook.write(os);
            os.flush();
            os.close();

            System.out.println("导出excel成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            System.out.println("导出excel失败！");

        }
    }
}
